const router = require('koa-router')()
const multer = require('@koa/multer');
const path = require('path');
const UUID = require('node-uuid');

const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, path.join(__dirname, '../public/upload'));
    },
    //修改文件名称
    filename: (req, file, cb) => {
      let filename = UUID.v1();
      filename = filename.replace(/-/g, '');
      if (file.originalname.indexOf('.') > 0) {
        let suffix = file.originalname.split('.').pop();
        filename = filename + '.' + suffix;
      }
      cb(null, filename);
    }
  })
});

/**
 * 文件上传
 * 保存到public/upload/
 * 返回文件的访问url
 */
 router.post('/upload', upload.single('file'), async (ctx, next) => {
  const domain = ctx.request.protocol + '://' + ctx.state.config.api_host;
  const fileurl = domain + '/upload/' + ctx.file.filename;
  ctx.body = {
    code: 200,
    msg: 'ok',
    data: {
      url: fileurl,
    }
  };
})



router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

module.exports = router
